import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Login = () => import('@/views/Login/Login.vue')
const Home = () => import('@/views/Home/Home.vue')
const Main = () => import('@/views/Main/Main.vue')
const User = () => import('@/views/User/User.vue')
const Test = () => import('@/views/Test/Test.vue')
const UserEdit = () => import('@/views/UserEdit/UserEdit.vue')
const Chat = () => import('@/views/Chat/Chat.vue')
const Search = () => import('@/views/Search/Search.vue')
const ArticleDetail = () => import('@/views/ArticleDetail/ArticleDetail.vue')
Vue.use(VueRouter)

// 处理路由版本问题报的警告 不影响使用
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }

  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/article/:id',
    component: ArticleDetail,
    name: 'article-detail',
    props: true
  },
  {
    path: '/search',
    component: Search,
    name: 'search'
  },
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  },
  {
    path: '/user/edit',
    component: UserEdit,
    name: 'user-edit'
  },
  {
    path: '/',
    component: Main,
    children: [
      {
        path: '',
        component: Home,
        name: 'home'
      },
      {
        path: 'user',
        component: User,
        name: 'user'
      },
      {
        path: 'test',
        component: Test,
        name: 'test'
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 这里定义的都是需要登录的页面
const pathArr = ['/user']

router.beforeEach((to, from, next) => {
  if (pathArr.indexOf(to.path) !== -1) {
    const tokenStr = store.state.tokenInfo.token
    if (tokenStr) {
      next()
    } else {
      next('/login?pre=' + to.fullPath)
    }
  } else {
    next()
  }
})

export default router
